package com.example.administrator.wallet.view.activity.mine.Personal.RealAuthentication;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.wallet.R;
import com.example.administrator.wallet.constant.Api;
import com.example.administrator.wallet.intf.IRequestCallback;
import com.example.administrator.wallet.intf.IRequestManager;
import com.example.administrator.wallet.model.bean.GetInfoBean;
import com.example.administrator.wallet.model.bean.RealImageBean;
import com.example.administrator.wallet.utils.DimbgUtils;
import com.example.administrator.wallet.utils.RequestFactory;
import com.example.administrator.wallet.utils.SharedPrefsUtil;
import com.google.gson.Gson;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.OkHttpFinal;
import cn.finalteam.okhttpfinal.OkHttpFinalConfiguration;
import cn.finalteam.okhttpfinal.RequestParams;
import mvp.presenter.HeaderPresenter;
import mvp.view.IHeaderView;
import okhttp3.Headers;

import static com.example.administrator.wallet.view.fragment.mine.MineFragment.getHttpBitmap;

public class HasRealAuthenticationAcitivity extends AppCompatActivity implements IHeaderView {

    private ImageButton mIb_back;
    private TextView mV_title;
    private Button bt_real_finish;
    private RelativeLayout activity_real_authentication_acitivity,rl_head,rl_back;
    private EditText et_real_name,et_real_ID_number;

    private View view;
    private HeaderPresenter headerPresenter;
    private File file;
    private static final int MSG_TAKE_PHOTO = 1;
    private File file_photo;
    private RequestParams params;
    int send = 0;
    private String head_URL = "";
    private String back_URL = "";
    private RealImageBean realImageBean;
    final IRequestManager reqequestManager = RequestFactory.getReqequestManager();
    private GetInfoBean getInfoBean;
    private String head,back;
    private static Bitmap bitmap_head,bitmap_back;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_real_authentication_acitivity);

        setStatuColor();
        Toast.makeText(getApplicationContext(), R.string.Messagependingreview,Toast.LENGTH_LONG).show();

        mIb_back = (ImageButton) findViewById(R.id.finish_img);
        mV_title = (TextView) findViewById(R.id.view_title);
        bt_real_finish = (Button) findViewById(R.id.bt_real_finish);
        activity_real_authentication_acitivity = (RelativeLayout) findViewById(R.id.activity_real_authentication_acitivity);
        et_real_name = (EditText) findViewById(R.id.et_real_name);
        et_real_ID_number = (EditText) findViewById(R.id.et_real_ID_number);
        rl_head = (RelativeLayout) findViewById(R.id.rl_head);
        rl_back = (RelativeLayout) findViewById(R.id.rl_back);


        mIb_back.setVisibility(View.VISIBLE);
        mV_title.setText(R.string.RealNameAuthentication);//实名认证
        headerPresenter = new HeaderPresenter(this, this);



        final Handler handler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 1:
                        rl_head.setBackground(bitmap2Drawable(bitmap_head));
                        break;
                    case 2:
                        rl_back.setBackground(bitmap2Drawable(bitmap_back));
                        break;

                }
            }
        };

        reqequestManager.httpPost(Api.BaseUrl + Api.get_info, Api.getinfo(SharedPrefsUtil.getValue(HasRealAuthenticationAcitivity.this, "wallet", "token", "")), new IRequestCallback() {
                        @Override
                        public void onSuccess(String Response) {
                            Gson gson = new Gson();
                            getInfoBean = gson.fromJson(Response, GetInfoBean.class);
                            if (getInfoBean.getCode() == 200){
//                                Toast.makeText(getApplicationContext(),"获取",Toast.LENGTH_LONG).show();
                                et_real_name.setText(getInfoBean.getData().getReal_name());
                                et_real_ID_number.setText(getInfoBean.getData().getId_number());
                                head = getInfoBean.getData().getId_card_img();
                                back = getInfoBean.getData().getId_card_img2();


                                // 显示
                                new Thread() {
                                    public void run() {
                                        bitmap_head = getHttpBitmap(head);
                                        Message msg = handler.obtainMessage();
                                        msg.obj = bitmap_head;
                                        msg.what = 1;
                                        handler.sendMessage(msg);

                                        bitmap_back = getHttpBitmap(back);
                                        msg = handler.obtainMessage();
                                        msg.obj = bitmap_back;
                                        msg.what = 2;
                                        handler.sendMessage(msg);
                                    }

                                    ;
                                }.start();
                            }
                        }
                        @Override
                        public void onFailure(String error) {
                        }
                    });


        rl_head.setBackground(Drawable.createFromPath(head));
        rl_back.setBackground(Drawable.createFromPath(back));
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();

        rl_head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                send = 1;
                initHead();
            }
        });

        rl_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                send = 2;
                initHead();
            }
        });

        bt_real_finish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(), R.string.Youhavesubmittedauthenticationinformation,Toast.LENGTH_SHORT).show();
//                if ("".equals(et_real_name.getText().toString()) | "".equals(et_real_ID_number.getText().toString()) | rl_head.getBackground() == null | rl_back.getBackground() == null){
//                    Toast.makeText(getApplicationContext(),R.string.Submissioncannotbeempty,Toast.LENGTH_SHORT).show();
//                }else{
//
//                    //实名验证上传
//                    reqequestManager.httpPost(Api.BaseUrl + Api.User_Information, Api.getUserInformation(SharedPrefsUtil.getValue(HasRealAuthenticationAcitivity.this, "wallet", "token", ""), "0"), new IRequestCallback() {
//                        @Override
//                        public void onSuccess(String Response) {
//                            Gson gson = new Gson();
//                            setRealBean = gson.fromJson(Response, SetRealBean.class);
//                            if (setRealBean.getCode() == 200){
//                                Toast.makeText(HasRealAuthenticationAcitivity.this, R.string.Submitted, Toast.LENGTH_SHORT).show();
//                                SharedPrefsUtil.putValue(HasRealAuthenticationAcitivity.this, "wallet", "authentication", "1");
//                            }
//                        }
//                        @Override
//                        public void onFailure(String error) {
//                        }
//                    });
//                }
            }


        });
        mIb_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
        overridePendingTransition(R.anim.pre_in_anim, R.anim.pre_out_anim);
    }
    private void initHead() {
        view = View.inflate(this, R.layout.popup_head, null);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

        final Button open_camera = (Button) view.findViewById(R.id.open_camera);
        final Button open_photo = (Button) view.findViewById(R.id.open_photo);
        final Button bt_cancel = (Button) view.findViewById(R.id.bt_cancel);

        new Handler().post(new Runnable() {
            @Override
            public void run() {
                final PopupWindow window = new PopupWindow(view, RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT, true);
                window.setFocusable(true);
                window.setTouchable(true);
                window.setOutsideTouchable(true);
                window.showAtLocation(activity_real_authentication_acitivity, Gravity.CENTER, 0, 0);
                Log.e("TAG-----", "OK");
                DimbgUtils.dimBackground(HasRealAuthenticationAcitivity.this, 0.5f);
                window.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        DimbgUtils.dimBackground(HasRealAuthenticationAcitivity.this, 1.0f);
                    }
                });
                //相机
                open_camera.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
//                        headerPresenter.takePhoto();
                        if (Build.VERSION.SDK_INT >= 23) {
                            int checkCallPhonePermission = ContextCompat.checkSelfPermission(HasRealAuthenticationAcitivity.this, Manifest.permission.CAMERA);
                            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                                ActivityCompat.requestPermissions(HasRealAuthenticationAcitivity.this, new String[]{Manifest.permission.CAMERA}, 222);
                                window.dismiss();
                                return;
                            } else {
                                headerPresenter.takePhoto(HasRealAuthenticationAcitivity.this);//调用具体方法
                                window.dismiss();

                            }
                        } else {
                            headerPresenter.takePhoto(HasRealAuthenticationAcitivity.this);//调用具体方法
                            window.dismiss();

                        }

                        window.dismiss();

                    }
                });

                //相册
                open_photo.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        headerPresenter.selectFromAlbum();
                        window.dismiss();
                    }
                });

                bt_cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        window.dismiss();
                    }
                });
            }
        });

    }
    Drawable bitmap2Drawable(Bitmap bitmap) {
        return new BitmapDrawable(bitmap);
    }
    //返回设置
    public void setHeaderBitmap(Bitmap bitmap) {
        if( send == 1 ){
            rl_head.setBackground(bitmap2Drawable(bitmap));
            File file_photo = headerPresenter.getFile(bitmap);
            OkHttpFinalConfiguration.Builder builder = new OkHttpFinalConfiguration.Builder();
            OkHttpFinal.getInstance().init(builder.build());
            RequestParams params = new RequestParams();
            params.addFormDataPart("access_token", SharedPrefsUtil.getValue(HasRealAuthenticationAcitivity.this, "wallet", "token", ""));
            params.addFormDataPart("image",file_photo);
            //身份证正面
            HttpRequest.post("https://wallet.kinlink.cn/api/certification/upload-image",params,new BaseHttpRequestCallback<RealImageBean>(){
                @Override
                protected void onSuccess(Headers headers, RealImageBean realImageBean) {
                    super.onSuccess(headers, realImageBean);
                    int code = realImageBean.getCode();
                    if (code == 200){
                        head_URL = realImageBean.getData().getUrlPath();
                    }
                }

                @Override
                public void onFailure(int errorCode, String msg) {
                    super.onFailure(errorCode, msg);

                }
            });
        }else if(send == 2){
            rl_back.setBackground(bitmap2Drawable( bitmap));
            file_photo = headerPresenter.getFile(bitmap);
            OkHttpFinalConfiguration.Builder builder = new OkHttpFinalConfiguration.Builder();
            OkHttpFinal.getInstance().init(builder.build());
            RequestParams param = new RequestParams();
            param.addFormDataPart("access_token", SharedPrefsUtil.getValue(HasRealAuthenticationAcitivity.this, "wallet", "token", ""));
            param.addFormDataPart("image",file_photo);

            //身份证背面上传
            HttpRequest.post("https://wallet.kinlink.cn/api/certification/upload-image",param,new BaseHttpRequestCallback<RealImageBean>(){
                @Override
                protected void onSuccess(Headers headers, RealImageBean realImageBean) {
                    super.onSuccess(headers, realImageBean);
                    int code = realImageBean.getCode();
                    if (code == 200){
                        back_URL = realImageBean.getData().getUrlPath();
                    }
                }

                @Override
                public void onFailure(int errorCode, String msg) {
                    super.onFailure(errorCode, msg);

                }
            });
        }
    }
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 点击取消按钮
        if (resultCode == RESULT_CANCELED) {
            return;
        }
        switch (requestCode) {
            case 2:
                Uri uri = data.getData();
                headerPresenter.startPhoto(uri);
                break;
            case 3:
                file = new File(Environment.getExternalStorageDirectory() + "/" + "iMon.jpg");
                headerPresenter.startPhoto(Uri.fromFile(file));
                break;
            case 4:
                if (data != null) {
                    headerPresenter.setView(data);
                }
                break;
            case MSG_TAKE_PHOTO:
                Log.i("main","to do");
                break;
        }
    }
    public void setStatuColor() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(getResources().getColor(android.R.color.white));
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        setMiuiStatusBarDarkMode(this, true);
        setMiuiStatusBarDarkMode(this, true);
    }

    //设置成白色的背景，字体颜色为黑色。
    public static boolean setMiuiStatusBarDarkMode(Activity activity, boolean darkmode) {
        Class<? extends Window> clazz = activity.getWindow().getClass();
        try {
            int darkModeFlag = 0;
            Class<?> layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
            Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
            darkModeFlag = field.getInt(layoutParams);
            Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
            extraFlagField.invoke(activity.getWindow(), darkmode ? darkModeFlag : 0, darkModeFlag);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static boolean setMeizuStatusBarDarkIcon(Activity activity, boolean dark) {
        boolean result = false;
        if (activity != null) {
            try {
                WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
                Field darkFlag = WindowManager.LayoutParams.class
                        .getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
                Field meizuFlags = WindowManager.LayoutParams.class
                        .getDeclaredField("meizuFlags");
                darkFlag.setAccessible(true);
                meizuFlags.setAccessible(true);
                int bit = darkFlag.getInt(null);
                int value = meizuFlags.getInt(lp);
                if (dark) {
                    value |= bit;
                } else {
                    value &= ~bit;
                }
                meizuFlags.setInt(lp, value);
                activity.getWindow().setAttributes(lp);
                result = true;
            } catch (Exception e) {
            }
        }
        return result;
    }

}
